package com.mock.ems.controller.distribution;

import com.jfinal.core.Controller;
import com.jfinal.plugin.activerecord.Db;
import com.jfinal.plugin.activerecord.Page;
import com.jfinal.plugin.activerecord.Record;
import com.mock.base.util.CollectionUtil;
import com.mock.base.util.DateUtil;
import com.mock.base.util.StringUtil;

import java.util.*;

/**
 * Created by MOCK on 2017/7/31.
 */
public class DistributionStatController extends Controller {

    public void index() {

        String currentDayRecordSQL = "select " +
                " IFNULL(sum(amount),0.00) as day_amount," +
                " IFNULL(sum(income),0.00) as day_income," +
                " IFNULL(sum(outcome),0.00) as day_outcome" +
                " from distribution_platform_detail where create_time >= ? and create_time < ? ";
        Record currentDayRecord = Db.findFirst(currentDayRecordSQL,
                DateUtil.getCurrentBeginTime(),
                DateUtil.getCurrentEndTime());

        if (null != currentDayRecord) {
            setAttr("currentDayPlatformRecord",currentDayRecord.getColumns());
        }

        String totalDayRecordSQL = "select " +
                " IFNULL(sum(amount),0.00) as total_amount," +
                " IFNULL(sum(income),0.00) as total_income," +
                " IFNULL(sum(outcome),0.00) as total_outcome" +
                " from distribution_platform_detail";
        Record totalPlatformRecord = Db.findFirst(totalDayRecordSQL);
        if (null != totalPlatformRecord) {
            setAttr("totalPlatformRecord",totalPlatformRecord.getColumns());
        }

        //消费者
        String currentDayConsumerSQL = "select sum(income) as day_consumer_income " +
                " from distribution_consumer_detail where create_time >= ? and create_time < ? ";
        Double currentDayConsumerIncome = Db.queryDouble(currentDayConsumerSQL,DateUtil.getCurrentBeginTime(),
                DateUtil.getCurrentEndTime());
        if (null == currentDayConsumerIncome) currentDayConsumerIncome = 0.00;
        setAttr("current_day_consumer_income",currentDayConsumerIncome);


        String totalConsumerSQL = "select sum(income) as total_consumer_income from distribution_consumer_detail";
        Double totalConsumerIncome = Db.queryDouble(totalConsumerSQL);
        if (null == totalConsumerIncome) totalConsumerIncome = 0.00;
        setAttr("total_consumer_income",totalConsumerIncome);


        //消费商
        String currentDayRecommanderSQL = "select sum(income) as day_recommander_income " +
                " from distribution_recommander_detail where create_time >= ? and create_time < ? ";
        Double currentDayRecommanderIncome = Db.queryDouble(currentDayRecommanderSQL,
                DateUtil.getCurrentBeginTime(),
                DateUtil.getCurrentEndTime());
        if (null == currentDayRecommanderIncome) currentDayRecommanderIncome = 0.00;
        setAttr("current_day_recommander_income",currentDayRecommanderIncome);


        String totalRecommanderSQL = "select sum(income) as total_recommander_income from distribution_recommander_detail";
        Double totalRecommanderIncome = Db.queryDouble(totalRecommanderSQL);
        if (null == totalRecommanderIncome) totalRecommanderIncome = 0.00;
        setAttr("total_recommander_income",totalRecommanderIncome);


        //品牌合作伙伴
        String currentDayCooperationPartnerSQL = "select sum(income) as day_cooperation_partner_income " +
                " from distribution_cooperation_partner_detail where create_time >= ? and create_time < ? ";
        Double currentDayCooperationPartnerIncome = Db.queryDouble(currentDayCooperationPartnerSQL,
                DateUtil.getCurrentBeginTime(),
                DateUtil.getCurrentEndTime());
        if (null == currentDayCooperationPartnerIncome) currentDayCooperationPartnerIncome = 0.00;
        setAttr("current_day_cooperation_partner_income",currentDayCooperationPartnerIncome);


        String totalCooperationPartnerSQL = "select sum(income) as day_cooperation_partner_income " +
                " from distribution_cooperation_partner_detail";
        Double totalCooperationPartnerIncome = Db.queryDouble(totalCooperationPartnerSQL);
        if (null == totalCooperationPartnerIncome) totalCooperationPartnerIncome = 0.00;
        setAttr("total_cooperation_partner_income",totalCooperationPartnerIncome);



        //品牌服务中心
        String currentDayServiceCenterSQL = "select sum(income) as day_service_center_income " +
                " from distribution_service_center_detail where create_time >= ? and create_time < ? ";
        Double currentDayServiceCenterIncome = Db.queryDouble(currentDayServiceCenterSQL,
                DateUtil.getCurrentBeginTime(),
                DateUtil.getCurrentEndTime());
        if (null == currentDayServiceCenterIncome) currentDayServiceCenterIncome = 0.00;
        setAttr("current_day_service_center_income",currentDayServiceCenterIncome);


        String totalServiceCenterSQL = "select sum(income) as day_service_center_income " +
                " from distribution_service_center_detail";
        Double totalServiceCenterIncome = Db.queryDouble(totalServiceCenterSQL);
        if (null == totalServiceCenterIncome) totalServiceCenterIncome = 0.00;
        setAttr("total_service_center_income",totalServiceCenterIncome);


        //获取商家统计信息
        String currentDayMerchantSQL = "select " +
                " IFNULL(sum(total_amount),0.00) as day_merchant_amount," +
                " IFNULL(sum(total_income),0.00) as day_merchant_income," +
                " IFNULL(sum(total_score),0.00) as day_merchant_score," +
                " IFNULL(sum(total_outcome),0.00) as day_merchant_outcome" +
                " from distribution_merchant_day_count where time >= ? and time < ? ";
        Record currentDayMerchant = Db.findFirst(currentDayMerchantSQL,
                DateUtil.toSeconds(DateUtil.getCurrentBeginTime().getTime()),
                DateUtil.toSeconds(DateUtil.getCurrentEndTime().getTime()));
        if (null != currentDayMerchant) {
            setAttr("currentDayMerchantRecord",currentDayMerchant.getColumns());
        }


        String totalMerchantSQL = "select " +
                " IFNULL(sum(total_amount),0.00) as total_merchant_amount," +
                " IFNULL(sum(total_income),0.00) as total_merchant_income," +
                " IFNULL(sum(total_score),0.00) as total_merchant_score," +
                " IFNULL(sum(total_outcome),0.00) as total_merchant_outcome" +
                " from distribution_merchant_day_count";
        Record totalMerchant = Db.findFirst(totalMerchantSQL);
        if (null != totalMerchant) {
            setAttr("totalMerchantRecord",totalMerchant.getColumns());
        }

        renderJsp("/page/distribution/distribution_stat.jsp");
    }


    public void pagination() {
        int pageNumber = getParaToInt("pageNumber");
        int pageSize = getParaToInt("pageSize");

        StringBuilder exceptSelectSQL = new StringBuilder(" from distribution_merchant_day_count where 1 = 1 ");
        List<Object> params = new ArrayList<Object>();

        String shopName = getPara("shop_name");
        if (StringUtil.isNotEmpty(shopName)) {
            Record shopRecord =Db.findFirst("select id_ from t_ou_shop where store_name_ like ? ",'%' + shopName + '%');
            exceptSelectSQL.append(" and shop_id = ? ");
            if (null != shopRecord) {
                params.add(shopRecord.getLong("id_"));
            }else {
                params.add(0L);
            }
        }

        Date begin_time = getParaToDate("begin_time");
        Date end_time = getParaToDate("end_time");

        if (null != begin_time && end_time == null) {
            exceptSelectSQL.append(" and time >= ? ");
            params.add(DateUtil.toSeconds(begin_time.getTime()));
        }

        if (null == begin_time && end_time != null) {
            exceptSelectSQL.append(" and time <= ? ");
            params.add(DateUtil.toSeconds(end_time.getTime()));
        }

        if (null != begin_time && null != end_time) {
            exceptSelectSQL.append(" and time >= ? and time <= ? ");
            params.add(DateUtil.toSeconds(begin_time.getTime()));
            params.add(DateUtil.toSeconds(end_time.getTime()));
        }

        Page<Record> recordList = null;
        if (params.size() == 0) {
            recordList = Db.paginate(pageNumber, pageSize, "select * ", exceptSelectSQL.toString());
        }else {
            recordList = Db.paginate(pageNumber, pageSize, "select * ", exceptSelectSQL.toString(),params.toArray());
        }

        if (CollectionUtil.isNotEmpty(recordList.getList())) {
            recordList.getList().forEach(item -> {
                Long user_id = item.getLong("user_id");
                Record user = Db.findById("user",user_id);
                if (null != user) {
                    item.set("show_owner_name",user.get("nick_name"));
                }
                Long shop_id = item.get("shop_id");
                Record shop_record = Db.findById("t_ou_shop","id_",shop_id);
                if (null != shop_record) {
                    item.set("show_name",shop_record.get("store_name_"));
                }

                item.set("time", DateUtil.format(new Date(item.getLong("time")*1000),"yyyy-MM-dd"));
            });
        }

        Map<String, Object> returnMap = new HashMap<String, Object>();
        returnMap.put("total", recordList.getTotalRow());
        returnMap.put("rows", recordList.getList());
        renderJson(returnMap);
    }
}
